<?php
/**
 * 后台微信用户控制器
 */
namespace Admin\Controller;
use Think\Controller;
use Common\Common;
class WxusersController extends Controller {

    var $i=0;
    var $users=array();//存储所有微信用户openid

    /**
     * 每晚执行此函数更新微信公众号粉丝
     */
    function index(){
        $this->getwxusers();
        $users=array();
        $u=array();
        foreach($this->users as $item){
            foreach($item['data'] as $item2){
                foreach($item2 as $item3){
                    $u['openid']=$item3;
                    $users[]=$u;
                }
            }
        }
        M('wx_openids')->where('1')->delete();
        M('wx_openids')->addAll($users);
        $openids=M()->query('SELECT openid FROM exp_wx_openids WHERE  openid  NOT  IN  ( SELECT openid FROM exp_wx_users)');//查询出所有新关注的微信用户
        $wechat=M('wechat_bindwechat')->select();
        $appid=$wechat[0]['appid'];
        $appsecret=$wechat[0]['appsecret'];
        $weixin = new Common\WeixinCommon();
        $access_token=$weixin->getAccessToken($appid,$appsecret);
        $wxusers=array();
        set_time_limit(0);
        foreach($openids as $o){
            $wxusers[]=$weixin->getUserInfoByOpenid($access_token,$o['openid']);
        }
        M('wx_users')->addAll($wxusers);
        echo 'success';
    }

    /**
     * 递归获取所有微信用户openid
     */
    function getwxusers($next_openid=''){
        $wechat=M('wechat_bindwechat')->select();
        $appid=$wechat[0]['appid'];
        $appsecret=$wechat[0]['appsecret'];
        $weixin = new Common\WeixinCommon();
        $access_token=$weixin->getAccessToken($appid,$appsecret);
        $arr=$weixin->getAllOpenid($access_token,$next_openid);
        if($arr['count']>0){
            $this->users[$this->i]=$arr;
            $this->i++;
            if($arr['next_openid']!=''){
                $this->getwxusers($arr['next_openid']);
            }
        }
    }
}